import { createRouter, createWebHistory } from 'vue-router'

// 使用import()进行路由懒加载，并添加注释标记使用webpack/rollup的动态导入特性
const routes = [
  {
    path: '/',
    component: () => import(/* webpackChunkName: "layout" */ '@/layout/MainLayout.vue'),
    children: [
      {
        path: 'device-discovery',
        name: 'DeviceDiscovery',
        component: () => import(/* webpackChunkName: "device" */ '@/views/DeviceDiscovery.vue'),
        meta: { keepAlive: true } // 启用组件缓存
      },
      {
        path: 'file-transfer',
        name: 'FileTransfer',
        component: () => import(/* webpackChunkName: "file" */ '@/views/FileTransfer.vue'),
        meta: { keepAlive: true } // 启用组件缓存
      },
      {
        path: 'messages',
        name: 'Messages',
        component: () => import(/* webpackChunkName: "messages" */ '@/views/Messages.vue'),
        meta: { keepAlive: true } // 启用组件缓存
      },
      {
        path: '',
        redirect: '/device-discovery'
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/device-discovery'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition // 如果存在savedPosition（例如通过后退按钮），则恢复之前的位置
    } else {
      return { top: 0 } // 否则滚动到顶部
    }
  }
})

export default router 